package com.hspedu.spring.component;

import com.hspedu.spring.annotation.Component;
import com.hspedu.spring.processor.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author xianYun
 * @version 1.0
 **/
@Component
public class HspBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (bean instanceof Car) {
            System.out.println("这是一个汽车");
        }
        System.out.println("后置处理器的 before 方法 bean类型：" + bean + " bean的名字：" + beanName);
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("后置处理器的 after 方法 bean类型：" + bean + " bean的名字：" + beanName);
        //假定需要代理的对象是 SmartDog
        if ("smartDog".equalsIgnoreCase(beanName)) {
            //使用 JDK 的动态代理返回代理对象
            Object proxyInstance = Proxy.newProxyInstance(HspBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("方法的名字：" + method.getName());
                    Object result = null;
                    if ("getSum".equalsIgnoreCase(method.getName())) {
                        SmartAnimalAspect.showBeginLog();//前置通知
                        result = method.invoke(bean, args);//执行目标方法
                        SmartAnimalAspect.showSuccessEndLog();//后置通知
                    }
                    return result;
                }
            });
            return proxyInstance;
        }
        return bean;

    }
}
